/*
 * File:    ClientChannelCache.java
 * Created: 16-May-2007
 * Version: $Id$
 *
 * COPYRIGHT (C) 2007, Bitgate Software, LLC.  All Rights Reserved.
 *
 * software@bitgatesoftware.com
 */

package com.bitgate.util.socket;

import java.util.HashMap;

/**
 * This is a <code>HashMap</code> based class that serves as a way for the <code>Service</code> class to lookup
 * active connections that it knows about.  This is used to transact with the <code>Worker</code>, which takes those
 * objects and passes them back and forth (by reference) to the <code>Service</code> to handle top-level communications.
 * Because this is a weak referenced cache, it means the items stored in cache can disappear at any point after the
 * underlying socket (or <code>ClientChannel</code>) is destroyed.
 * 
 * @author khollis
 */
public class ClientChannelCache
{
	private final HashMap<String, ClientChannel> channelCache;
	
	private static final ClientChannelCache _default = new ClientChannelCache();
	private static final Object CHANNEL_CACHE_OBJECT = new Object();
	
	private ClientChannelCache()
	{
		this.channelCache = new HashMap<String, ClientChannel>();
	}
	
	/**
	 * Retrieves a <code>ClientChannel</code> object by serial ID.
	 * 
	 * @param clientId The client ID to look up.
	 * @return <code>ClientChannel</code> associated with the object, or <code>null</code> if not found or the reference was lost.
	 */
	public ClientChannel get(String clientId)
	{
		synchronized(CHANNEL_CACHE_OBJECT) {
			return this.channelCache.get(clientId);
		}
	}
	
	/**
	 * Stores a <code>ClientChannel</code> object for quick lookup.
	 * 
	 * @param clientId The ID for the client entry.
	 * @param cChannel The <code>ClientChannel</code> reference to store.
	 */
	public void set(String clientId, ClientChannel cChannel)
	{
		synchronized(CHANNEL_CACHE_OBJECT) {
			this.channelCache.put(clientId, cChannel);
		}
	}
	
	/**
	 * Returns the singleton instance of this class.
	 * 
	 * @return <code>ClientChannelCache</code> object.
	 */
	public static ClientChannelCache getDefault()
	{
		return _default;
	}
}